<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

/**
 * 消息模型
 * @author www.dingwei.cn
 */

class ConsumerMessageModel extends MY_Model{
    public $tbMessage = 'consumer_message';
    public $tbMessageViewed = 'consumer_message_viewed';
    public $tbUser = 'consumer';

    // 送货订单提示
    public $TIPS = array(
        '1'=>'',
        '2'=>'等待商家发货',
        '3'=>'查询物流跟踪订单',
        '4'=>'您的订单已签收',
        '5'=>'',
        '6'=>'',
        '7'=>'',
        '8'=>'',
    );
// 到店订单提示
    public $STORE_TIPS = array(
        '1'=>'',
        '2'=>'',
        '3'=>'到店展示二维码核销',
        '4'=>'订单核销成功',
        '5'=>'',
        '6'=>'',
        '7'=>'',
        '8'=>'',
    );
    /**
     * 获取消息数量
     * @param integer $consumerId
     * @param integer $type             1 订单消息    2 系统消息
     * @return array
     * @author zyl
     */
    public function getMessageTotal($consumerId,$type){
    	
    	$this->db->select('m.id,b.consumer_id,b.order_id');
    	if ($type == 1){
    		$this->db
    		->where(array('m.consumer_id' => $consumerId))
    		->where('b.consumer_id is null')
    		->where_in('m.type', array(1,2))
            ->group_by('m.id');

    	}elseif ($type == 2){
            $this->db
                ->where(array('m.consumer_id' => $consumerId))
                ->where('b.consumer_id is null')
                ->where_in('m.type', array(3,4))
                ->group_by('m.order_id');
        }else{
    		$this->db
    		->where(array('m.consumer_id' => $consumerId))
    		->where('b.consumer_id is null')
    		->where_in('m.type', array(1,2,3,4))
            ->group_by('m.order_id');
    	}

        $this->db->join($this->tbMessageViewed.' b','m.id = b.message_id','LEFT');
    	$tA = $this->count($this->tbMessage.' m');

    	return $tA;
    }
    
    /**
     * app获取消息
     * @param integer $consumerId 消费者id
     * @param integer $type 类型 1-系统消息  3-订单消息
     * @param number $page
     * @return array|string|array|array[]|number[]|unknown[]
     * @author zyl
     */
    public function appGetList($consumerId,$type,$page = 1){
    	
    	if (! $consumerId || ! $type){
    		return array();
    	}
    	
    	if ($type == 1){
    		$this->db
    		->where(array('m.consumer_id' => $consumerId))
    		->where('(b.is_delete <> 2 or b.is_delete is null)')
    		->where_in('m.type',[1,2])
    		->where('(b.is_delete <> 2 or b.is_delete is null)')
            ->group_by('m.id');
    	}else{
    		$this->db
    		->where(array('m.consumer_id' => $consumerId))
    		->where_in('m.type', array(3,4))
    		->where('(b.is_delete <> 2 or b.is_delete is null)')
            ->group_by('m.order_id');
    	}
    	get_instance()->loadModel('ConsumerOrderModel', 'mOrder', 'consumer');
    	//用id倒序排序
    	$this->db->select('m.id,m.title,m.type,m.content,m.addtime,b.message_id as is_read,m.order_id,o.code,
                        o.status,o.reality_amount,o.addtime as time,o.expense_type,os.status as service_status,
                        os.refund_amount,os.addtime as service_time,os.code as service_code')
    	->join($this->tbMessageViewed.' b','m.id = b.message_id and b.consumer_id = '.$consumerId,'LEFT')
    	->join($this->mOrder->tbOrder.' o','o.id = m.order_id and m.type = 3','LEFT')
    	->join($this->mOrder->tbOrderService.' os','os.id = m.order_id and m.type = 4','LEFT')
    	->order_by('m.id desc');
    	$tA = $this->appPage($this->tbMessage.' m', $page);
//    	echo $this->db->last_query();
    	foreach ($tA['list'] as $k => $v){
            $tA['list'][$k]['time']  = $v['time']?$v['time']:'';
            $tA['list'][$k]['code']  = $v['code']?$v['code']:'';
            $tA['list'][$k]['status']  = $v['status']?$v['status']:'';
    	    if($v['status']){//订单
                if ($v['expense_type'] == 1){
                    $tA['list'][$k]['status'] = $this->mOrder->STATUS[$v['status']];
                    $tA['list'][$k]['tips']  = $this->TIPS[$v['status']];
                }elseif ($v['expense_type'] == 2){
                    $tA['list'][$k]['status']  = $this->mOrder->STORE_STATUS[$v['status']];
                    $tA['list'][$k]['tips']  = $this->STORE_TIPS[$v['status']];
                }
                $tA['list'][$k]['amount']  = $v['reality_amount'];
                $tA['list'][$k]['time']  = dateFormat($v['time'], true);
            }
            if($v['service_status']){//售后单
                $tA['list'][$k]['status']  = $this->mOrder->SERVICE_TYPE[$v['service_status']];
                $tA['list'][$k]['tips']  = $v['content'];
                $tA['list'][$k]['amount']  = $v['refund_amount'];
                $tA['list'][$k]['code']  = $v['service_code'];
                $tA['list'][$k]['time']  = dateFormat($v['service_time'], true);
            }
    		if (dateFormat($v['addtime']) == dateFormat(time())){
    			$tA['list'][$k]['addtime'] = date('H:i', $v['addtime']);
    		}else{
    			$tA['list'][$k]['addtime'] = dateFormat($v['addtime']);
    		}
    		$tA['list'][$k]['is_read'] = $v['is_read'] > 0 ? '2' : '1'; // 1 未读  2 已读
    		
    		$tA['list'][$k]['order_id'] = empty($v['order_id']) ? '0' : $v['order_id']; //

            unset($tA['list'][$k]['service_status'],$tA['list'][$k]['expense_type'],$tA['list'][$k]['reality_amount'],
                    $tA['list'][$k]['refund_amount'],$tA['list'][$k]['service_time'],$tA['list'][$k]['service_code']);
    	}
    	return $tA['list'];
    }
    
    /**
     * 获取消息详情
     * @param integer $id 消息id
     * @param number $consumerId 消费者id
     * @param number $serviceId 售后id
     * @param number $orderId 订单id
     * @return array|array
     * @author zyl
     */
    public function getInfo($id,$consumerId = 0,$serviceId = 0, $orderId = 0){
    	if ( ! $id && ! $serviceId && !$orderId){

    		return array();
    	}
    	if($id){
    	    $this->db->where('m.id', $id);
        }
        if($serviceId){
            $this->db->where(array('m.type' => 4, 'm.order_id' => $serviceId));
        }
        if($orderId){
            $this->db->where(array('m.type' => 3, 'm.order_id' => $orderId));
        }
        if($consumerId){
            $this->db->where('m.consumer_id', $consumerId);
        }

    	$this->db
    	->select('m.id,m.title,m.order_id,m.type,m.content,m.content_detail,m.addtime,v.message_id as viewed')
        ->join($this->tbMessageViewed.' v', 'v.message_id = m.id', 'left');;
    	$tA = $this->getOne($this->tbMessage.' m');
        if ($tA) {
            $tA['viewed'] = isset($tA['viewed']) ? '2' : '1'; //1未读 2已读
            $tA['addtime'] = date('Y年m月d日 H:i',$tA['addtime']);
            $tA['content_detail'] = $tA['content_detail']?str_replace('{base_url}', base_url(), $tA['content_detail']):'';
        }

    	return $tA;
    }
    
    
    /**
     * 获取该订单消息未读的消息
     * @param unknown $consumerId
     * @param unknown $orderId
     * @return array
     */
    public function getOrderMsg($consumerId,$orderId){
    
    	$this->db
    	->select('m.id,m.order_id,b.message_id')
    	->where('m.consumer_id',$consumerId)
    	->where('m.order_id',$orderId)
    	->where('b.message_id is null')
    	->where('m.type',3)
    	->join($this->tbMessageViewed.' b','m.id = b.message_id','left');
    	$tA = $this->getAll($this->tbMessage.' m');
    	//echo $this->db->last_query();
    	return $tA;
    }
    
    /**
     * 后台获取数据列表
     * @return array
     * @author heyu
     */
    public function adminPcGetList(){
        $title = trim(get('title'));
        $type = (int)get('type');
        $star = strtotime(get('star'));
        $end = strtotime(get('end'));
        $iSortCol_0 = (int)get('iSortCol_0');//针对某一列进行排序
        $sSortDir_0 = trim(get('sSortDir_0'));//排序方式，值为"asc"或者"desc"

        if($title){
            $this->db->like(array('title' => $title));
        }
        if ($type){
            $this->db->where(array('type' => $type));
        }
        if($star){
            $this->db->where('addtime >=', $star);
        }
        if($end){
            $this->db->where('addtime <= ', strtotime('+1day', $end));
        }

        if ($iSortCol_0 == 3){
            $this->db->order_by('addtime', $sSortDir_0);
        }else{
            $this->db->order_by('addtime', 'desc');
        }

        $this->db->select('id,type,title,content,addtime,count(addtime) as total')
            ->group_by('addtime');
        return $this->pagination($this->tbMessage);
    }

    /**
     * 保存信息
     * @param	array	$data	保存数据
     * @param	integer $id		消息id
     * @param	integer $orderId 订单id
     * @param	integer $saleId 售后订单id
     * @return	boolean
     * @author heyu
     */
    public function save($data, $id = 0, $orderId = 0, $saleId = 0){

        if( ! $data) return false;
        if($id){
            $this->db->where(array('id' => $id));
            if($this->update($this->tbMessage, $data)){
                return true;
            }
        }elseif($orderId){
            $this->db->where(array('order_id' => $orderId, 'type' => 3));
            if($this->update($this->tbMessage, $data)){
                return true;
            }
        }elseif($saleId){
            $this->db->where(array('order_id' => $saleId, 'type' => 4));
            if($this->update($this->tbMessage, $data)){
                return true;
            }
        }
        else{
            if($id = $this->insert($this->tbMessage, $data)){
                return $id;
            }
        }
    }
    
    /**
     * 保存信息
     * @param	array	$data	保存数据
     * @param	integer $id		用户id
     * @return	boolean
     * @author heyu
     */
    public function saveBatch($data, $id = 0, $key = ''){

        if( ! $data) return false;
        if($id){
            $this->db->where(array('id' => $id));
            if($this->updateBatch($this->tbMessage, $data)){
                return true;
            }
        }elseif ($key == 'order_id'){
            return $this->updateBatch($this->tbMessage, $data, 'order_id');
        }else{
            if($id = $this->insertBatch($this->tbMessage, $data)){
                return $id;
            }
        }
    }
    
    /**
     * 获取该消息状态
     * @param integer $id
     * @param integer $consumerId
     * @return array
     * @author zyl
     */
    public function getMsgStatus($id,$consumerId){
    	$this->db->where(array('message_id' => $id,'consumer_id'=>$consumerId));
    	return $this->getOne($this->tbMessageViewed);
    }
    /**
     * 保存信息
     * @param	array	$data	保存数据
     * @param	integer $id		消息id
     * @return	boolean
     * @author heyu
     */
    public function saveStatus($data, $id = 0,$consumerId = 0){

        if( ! $data) return false;
        if($id && $consumerId){
        	
        	if ( ! $this->getMsgStatus($id,$consumerId)){
        		//没有
        		$tData = array(
        				'consumer_id'=>$consumerId,
        				'message_id'=>$id,
        				'is_delete'=>0,
        				'addtime'=>time(),
        		);
        		if ( ! $this->insert($this->tbMessageViewed, $tData)){
        			return false;
        		}
        	}
        	
        	$this->db->where(array('message_id' => $id,'consumer_id'=>$consumerId));
            $query = $this->update($this->tbMessageViewed, $data);
            return $query === false ? false : true;
        	
        }else{
        	return $this->insert($this->tbMessageViewed, $data);
        }
    }

    /**
     * 保存查看记录信息
     * @param	array	$data	保存数据
     * @return	boolean
     * @author heyu
     */
    public function saveView($data, $id = 0){

        if( ! $data) return false;
        if($id){
            $this->db->where(array('message_id' => $id));
            if($this->update($this->tbMessageViewed, $data)){
                return true;
            }
        }else{
            if($id = $this->insert($this->tbMessageViewed, $data)){
                return $id;
            }
        }

    }

    /**
     * 批量保存
     * @param $data
     * @return bool
     * @author heyu
     */
    public function batchSave($data){
        return $this->insertBatch($this->tbMessage, $data);
    }

    /**
     * 获取消息推送的人
     * @author heyu
     */
    public function getConsumerDetail(){
        $addTime = (int)get('addtime');
        if (!$addTime) return false;
        $realname = get('realname');
        $nickname = get('nickname');
        $mobile = get('mobile');
        if ($realname){
            $this->db->like(array('realname' => $realname));
        }
        if ($nickname){
            $this->db->like(array('nickname' => $nickname));
        }
        if ($mobile){
            $this->db->like(array('mobile' => $mobile));
        }
        $this->db->select('u.portrait,u.realname,u.nickname,u.mobile')
            ->join($this->tbUser.' u', 'm.consumer_id=u.id')
            ->where('m.addtime', $addTime)
            ->order_by('u.id desc');
        return $this->pagination($this->tbMessage.' m');
    }

    /**
     * 删除查看记录
     * @param $consumerId
     * @param $messageId
     * @return bool
     */
    public function deleteView($consumerId, $messageId, $orderId = 0){
        if (!$orderId && !$messageId){
            return false;
        }
        if($orderId){
            $this->db->where(array('order_id' => $orderId));
        }
        if($messageId){
            $this->db->where(array('message_id' => $messageId));
        }

        $this->db->where(array('consumer_id' => $consumerId));

        return $this->delete($this->tbMessageViewed);
    }

    /**
     * 删除消息
     * @param $messageId
     * @return bool
     */
    public function deleteMsg($orderId, $consumerId = 0){

        if (!$orderId){
            return false;
        }
        if($consumerId){
            $this->db->where('consumer_id', $consumerId);
        }
        $this->db->where(array('order_id' => $orderId));

        return $this->delete($this->tbMessage);
    }

    /**
     * 消息类型
     * @param $key
     * @return mixed|string
     */
    public function getType($key = 0){
        $config = array(
            1 => '系统消息(所有人)',
            2 => '系统消息（指定人）',
            3 => '订单消息',
            4 => '售后订单消息',
        );
        if( ! $key){
            return $config;
        }
        return $config[$key];
    }
}